﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'daily_events_logic.dart';

/// 事件选择页面
class EventSelectionView extends GetView<DailyEventsLogic> {
  final String category;
  final String title;

  const EventSelectionView({
    super.key,
    required this.category,
    required this.title,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: Text(title),
        centerTitle: true,
        elevation: 0,
        backgroundColor: Colors.transparent,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () => Get.back(),
        ),
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: EdgeInsets.all(20.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        title,
                        style: TextStyle(
                          fontSize: 18.sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.black87,
                        ),
                      ),
                      SizedBox(height: 20.h),
                      _buildEventGrid(),
                    ],
                  ),
                ),
              ),
            ),
            // 底部完成按钮
            Container(
              padding: EdgeInsets.all(20.w),
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.1),
                    spreadRadius: 1,
                    blurRadius: 8,
                    offset: const Offset(0, -2),
                  ),
                ],
              ),
              child: SafeArea(
                child: ElevatedButton(
                  onPressed: () => Get.back(),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.orange,
                    foregroundColor: Colors.white,
                    padding: EdgeInsets.symmetric(vertical: 16.h),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(25.r),
                    ),
                  ),
                  child: Text(
                    '完成',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建事件网格
  Widget _buildEventGrid() {
    return Obx(() {
      final allEvents = _getAllEventsForCategory();
      final selectedEvents = _getSelectedEventsForCategory();
      
      return Wrap(
        spacing: 12.w,
        runSpacing: 12.h,
        children: [
          ...allEvents.map((event) => _buildEventChip(event, selectedEvents.contains(event))),
          _buildAddEventChip(),
        ],
      );
    });
  }

  /// 获取指定类别的所有事件
  List<String> _getAllEventsForCategory() {
    switch (category) {
      case 'dailyCheckIn':
        return [
          '喝水', '洗手', '站立', '晒太阳', '运动', '冥想', '阅读', '早睡', '早起', '刷牙'
        ];
      case 'entertainment':
        return [
          '电影', '追剧', '音乐', '电子游戏', '阅读', '运动', '派对', '旅行', '观看比赛',
          '观赏类活动', '社交互动类', '学习探索类', '虚拟娱乐类', '实践型活动', '工作狂'
        ];
      case 'symptoms':
        return [
          '疼痛', '感冒', '胃肠道', '皮肤问题', '头痛', '疲劳', '失眠', '焦虑', '抑郁',
          '发烧', '咳嗽', '流鼻涕', '恶心', '呕吐', '腹泻', '便秘'
        ];
      default:
        return [];
    }
  }

  /// 获取指定类别已选择的事件
  List<String> _getSelectedEventsForCategory() {
    switch (category) {
      case 'dailyCheckIn':
        return controller.state.dailyCheckInEvents.toList();
      case 'entertainment':
        return controller.state.entertainmentEvents.toList();
      case 'symptoms':
        return controller.state.symptomsEvents.toList();
      default:
        return [];
    }
  }

  /// 构建事件芯片
  Widget _buildEventChip(String event, bool isSelected) {
    return GestureDetector(
      onTap: () {
        if (isSelected) {
          controller.removeEvent(category, event);
        } else {
          controller.addEvent(category, event);
        }
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
        decoration: BoxDecoration(
          color: isSelected ? Colors.orange[100] : Colors.grey[200],
          borderRadius: BorderRadius.circular(25.r),
          border: isSelected 
              ? Border.all(color: Colors.orange, width: 2)
              : Border.all(color: Colors.grey[300]!, width: 1),
        ),
        child: Text(
          event,
          style: TextStyle(
            fontSize: 14.sp,
            color: isSelected ? Colors.orange[700] : Colors.grey[700],
            fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  /// 构建添加事件芯片
  Widget _buildAddEventChip() {
    return GestureDetector(
      onTap: _showAddEventDialog,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(25.r),
          border: Border.all(color: Colors.grey[300]!, width: 1),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.add,
              size: 20.sp,
              color: Colors.orange,
            ),
            SizedBox(width: 8.w),
            Text(
              '添加',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.orange,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 显示添加事件对话框
  void _showAddEventDialog() {
    final textLogic = TextEditingController();
    
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Container(
          padding: EdgeInsets.all(24.w),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '添加自定义事件',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
              ),
              SizedBox(height: 20.h),
              TextField(
                controller: textLogic,
                decoration: InputDecoration(
                  hintText: '请输入事件名称',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  contentPadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                ),
                autofocus: true,
              ),
              SizedBox(height: 24.h),
              Row(
                children: [
                  Expanded(
                    child: TextButton(
                      onPressed: () => Get.back(),
                      child: Text(
                        '取消',
                        style: TextStyle(
                          fontSize: 16.sp,
                          color: Colors.grey[600],
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 16.w),
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () {
                        final eventName = textLogic.text.trim();
                        if (eventName.isNotEmpty) {
                          controller.addEvent(category, eventName);
                          Get.back();
                        }
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.orange,
                        foregroundColor: Colors.white,
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(25.r),
                        ),
                      ),
                      child: Text(
                        '确定',
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: true,
    );
  }
}
